<!--
 * @Description: 业务员管理页 - 查看销售员的客户跟进情况、订单完成量等数据
 * @Author: lujq
 * @Date: 2025-08-25
 * @LastEditors: lujq
 * @LastEditTime: 2025-08-25 16:10:00
-->
<template>
  <div class="sales-management">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="销售员姓名" clearable @keyup.enter="fetchData" />
          </el-form-item>
          <el-form-item label="业绩排序">
            <el-select v-model="searchForm.sortBy" placeholder="排序字段" style="width: 160px">
              <el-option label="客户数量" value="customerCount" />
              <el-option label="订单完成量" value="completedOrders" />
              <el-option label="销售额" value="revenue" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 业绩概览 -->
    <el-row :gutter="20" style="margin-top: 16px;">
      <el-col :xs="24" :sm="12" :md="6" v-for="item in overviewStats" :key="item.title">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon" :style="{ backgroundColor: item.color }">
              <el-icon :size="20">
                <component :is="item.icon" />
              </el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">{{ item.title }}</div>
              <div class="card-value">{{ item.value }}</div>
              <div class="card-desc">{{ item.desc }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售员业绩表格与图表 -->
    <el-row :gutter="20" style="margin-top: 16px;">
      <!-- 业绩排行榜 -->
      <el-col :xs="24" :lg="14">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">销售员业绩排行</span>
              <el-button type="primary" size="small" @click="exportReport">导出报表</el-button>
            </div>
          </template>
          
          <el-table :data="salesmanList" border :loading="loading" row-key="id" stripe>
            <el-table-column type="index" label="排名" width="60" align="center">
              <template #default="{ $index }">
                <el-tag v-if="$index < 3" :type="getRankType($index)" size="small">{{ $index + 1 }}</el-tag>
                <span v-else>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="销售员" min-width="120">
              <template #default="{ row }">
                <div class="salesman-info">
                  <el-avatar :size="32" :src="row.avatar" :icon="UserFilled" />
                  <div style="margin-left: 8px;">
                    <div>{{ row.name }}</div>
                    <div class="text-secondary">{{ row.role }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="customerCount" label="客户数量" width="100" align="center" />
            <el-table-column prop="completedOrders" label="完成订单" width="100" align="center" />
            <el-table-column prop="revenue" label="销售额(万元)" width="120" align="right">
              <template #default="{ row }">
                <span style="color: #67C23A;">{{ (row.revenue / 10000).toFixed(1) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="followupScore" label="跟进评分" width="100" align="center">
              <template #default="{ row }">
                <el-rate v-model="row.followupScore" :max="5" disabled text-color="#FF9900" />
              </template>
            </el-table-column>
            <el-table-column prop="lastContact" label="最近联系" width="140" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="viewCustomers(row)">客户列表</el-button>
                <el-button link type="success" size="small" @click="viewOrders(row)">订单详情</el-button>
                <el-button link type="warning" size="small" @click="viewStats(row)">数据分析</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pager">
            <el-pagination
               background
               layout="prev, pager, next, sizes, jumper, total"
               :total="salesmanList.length"
               :current-page="pagination.page"
               :page-size="pagination.pageSize"
               @current-change="onPageChange"
               @size-change="onPageSizeChange"
             />
          </div>
        </el-card>
      </el-col>

      <!-- 业绩图表 -->
      <el-col :xs="24" :lg="10">
        <el-card class="chart-card">
          <template #header>
            <span class="card-title">月度业绩趋势</span>
          </template>
          <div ref="performanceChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 客户跟进情况 -->
    <el-row style="margin-top: 16px;">
      <el-col :span="24">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">客户跟进情况汇总</span>
              <div>
                <el-tag type="danger" v-if="overdueTasks > 0">逾期跟进：{{ overdueTasks }}</el-tag>
                <el-tag type="warning" style="margin-left: 8px;" v-if="todayTasks > 0">今日跟进：{{ todayTasks }}</el-tag>
              </div>
            </div>
          </template>

          <el-table :data="followupSummary" border stripe>
            <el-table-column prop="salesman" label="销售员" width="120">
              <template #default="{ row }">
                <div class="salesman-info">
                  <el-avatar :size="28" :src="row.avatar" :icon="UserFilled" />
                  <span style="margin-left: 8px;">{{ row.salesman }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="totalCustomers" label="总客户数" width="100" align="center" />
            <el-table-column prop="activeCustomers" label="活跃客户" width="100" align="center" />
            <el-table-column prop="overdueFollowups" label="逾期跟进" width="100" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.overdueFollowups > 0" type="danger" size="small">{{ row.overdueFollowups }}</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="todayFollowups" label="今日跟进" width="100" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.todayFollowups > 0" type="warning" size="small">{{ row.todayFollowups }}</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="avgResponseTime" label="平均响应时间" width="120" align="center" />
            <el-table-column prop="conversionRate" label="转化率" width="100" align="center">
              <template #default="{ row }">
                <span :style="{ color: row.conversionRate > 30 ? '#67C23A' : '#E6A23C' }">{{ row.conversionRate }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="lastActiveDate" label="最后活跃" width="140" />
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="viewFollowupDetails(row)">跟进详情</el-button>
                <el-button link type="success" size="small" @click="assignTasks(row)">分配任务</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
/**
 * @description 业务员管理页逻辑：
 * - 统计各销售员客户数量、订单完成情况、销售业绩
 * - 监控客户跟进状态，标记逾期和待处理任务
 * - 提供业绩排行与跟进效率分析
 */
import { ref, reactive, computed, onMounted } from 'vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { UserFilled, TrendCharts, Wallet, DataAnalysis } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { http } from '@/api/index'
import { getOrderList } from '@/api/order'
import type { Order, Customer, User } from '@/types'

// 搜索表单与分页
const searchForm = reactive<{ keyword: string; sortBy: string; dateRange: [string, string] | null }>({
  keyword: '',
  sortBy: 'revenue',
  dateRange: [dayjs().startOf('month').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
})
const pagination = reactive({ page: 1, pageSize: 10, total: 0 })
const loading = ref(false)

// 源数据
const users = ref<User[]>([])
const customers = ref<Customer[]>([])
const orders = ref<Order[]>([])

// 概览统计
const overviewStats = ref([
  {
    title: '总销售员',
    value: '0',
    desc: '在职销售人员',
    icon: UserFilled,
    color: '#409EFF',
  },
  {
    title: '活跃销售员',
    value: '0',
    desc: '本月有业绩',
    icon: TrendCharts,
    color: '#67C23A',
  },
  {
    title: '平均业绩',
    value: '0万',
    desc: '人均销售额',
    icon: Wallet,
    color: '#E6A23C',
  },
  {
    title: '客户转化率',
    value: '0%',
    desc: '平均转化情况',
    icon: DataAnalysis,
    color: '#F56C6C',
  },
])

// 逾期任务与今日任务数
const overdueTasks = ref(0)
const todayTasks = ref(0)

// 图表引用
const performanceChart = ref<HTMLElement>()
let performanceChartInstance: echarts.ECharts
// 路由
const router = useRouter()

/**
 * 销售员业绩列表（聚合计算）
 */
const salesmanList = computed(() => {
  // 按销售经理字段关联
  const salesmanMap = new Map<string, {
    id: string
    name: string
    role: string
    avatar: string
    customerCount: number
    completedOrders: number
    revenue: number
    followupScore: number
    lastContact: string
  }>()

  // 统计客户数量
  customers.value.forEach(c => {
    if (c.salesManager) {
      if (!salesmanMap.has(c.salesManager)) {
        salesmanMap.set(c.salesManager, {
          id: c.salesManager,
          name: c.salesManager,
          role: '销售专员',
          avatar: '/images/avatars/staff.svg',
          customerCount: 0,
          completedOrders: 0,
          revenue: 0,
          followupScore: 4,
          lastContact: c.lastContactDate || '未联系',
        })
      }
      const item = salesmanMap.get(c.salesManager)!
      item.customerCount++
    }
  })

  // 统计订单完成量和销售额
  orders.value.forEach(o => {
    if (o.status === 'delivered' && o.customerName) {
      const customer = customers.value.find(c => c.name === o.customerName)
      if (customer?.salesManager) {
        const item = salesmanMap.get(customer.salesManager)
        if (item) {
          item.completedOrders++
          item.revenue += Number(o.finalAmount || 0)
        }
      }
    }
  })

  const result = Array.from(salesmanMap.values())
  
  // 按选定字段排序
  result.sort((a, b) => {
    const key = searchForm.sortBy as keyof typeof a
    return Number(b[key]) - Number(a[key])
  })

  // 应用关键词过滤
  if (searchForm.keyword) {
    return result.filter(item => item.name.includes(searchForm.keyword))
  }

  return result
})

/**
 * 客户跟进汇总
 */
const followupSummary = computed(() => {
  const summaryMap = new Map<string, any>()

  customers.value.forEach(c => {
    if (c.salesManager) {
      if (!summaryMap.has(c.salesManager)) {
        summaryMap.set(c.salesManager, {
          salesman: c.salesManager,
          avatar: '/images/avatars/staff.svg',
          totalCustomers: 0,
          activeCustomers: 0,
          overdueFollowups: 0,
          todayFollowups: 0,
          avgResponseTime: '2小时',
          conversionRate: Math.floor(Math.random() * 40) + 20, // 模拟转化率20-60%
          lastActiveDate: dayjs().subtract(Math.floor(Math.random() * 7), 'day').format('MM-DD'),
        })
      }
      
      const item = summaryMap.get(c.salesManager)!
      item.totalCustomers++
      
      // 活跃客户（最近30天有联系）
      if (c.lastContactDate && dayjs().diff(dayjs(c.lastContactDate), 'day') <= 30) {
        item.activeCustomers++
      }
      
      // 逾期跟进（超过7天未联系且非潜在客户）
      if (c.lastContactDate && dayjs().diff(dayjs(c.lastContactDate), 'day') > 7 && c.status === 'active') {
        item.overdueFollowups++
      }
      
      // 今日跟进（模拟）
      if (Math.random() < 0.2) { // 20%概率有今日跟进
        item.todayFollowups++
      }
    }
  })

  return Array.from(summaryMap.values())
})

/**
 * 获取排名标签类型
 */
const getRankType = (index: number) => {
  return ['danger', 'warning', 'success'][index] || ''
}

/**
 * 加载数据：用户、客户、订单
 */
async function fetchData() {
  try {
    loading.value = true
    
    // 加载用户
    const { data: userResp } = await http.get<{ items: User[] }>(`/users?page=1&pageSize=1000`)
    users.value = userResp.items || []
    
    // 加载客户
    const { data: customerResp } = await http.get<{ items: Customer[] }>(`/customers?page=1&pageSize=10000`)
    customers.value = customerResp.items || []
    
    // 加载订单
    const { data: orderResp } = await getOrderList({
      page: 1,
      pageSize: 10000,
      dateRange: searchForm.dateRange || undefined,
    })
    orders.value = orderResp.list

    updateOverviewStats()
    updateTaskCounts()
  } catch (e) {
    console.error(e)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 更新概览统计
 */
function updateOverviewStats() {
  const salesmen = Array.from(new Set(customers.value.map(c => c.salesManager).filter(Boolean)))
  const activeSalesmen = salesmanList.value.filter(s => s.completedOrders > 0).length
  const totalRevenue = salesmanList.value.reduce((sum, s) => sum + s.revenue, 0)
  const avgRevenue = salesmen.length > 0 ? totalRevenue / salesmen.length : 0
  const avgConversion = followupSummary.value.length > 0 ? 
    followupSummary.value.reduce((sum, f) => sum + f.conversionRate, 0) / followupSummary.value.length : 0

  overviewStats.value[0].value = String(salesmen.length)
  overviewStats.value[1].value = String(activeSalesmen)
  overviewStats.value[2].value = (avgRevenue / 10000).toFixed(1) + '万'
  overviewStats.value[3].value = avgConversion.toFixed(1) + '%'
}

/**
 * 更新任务计数
 */
function updateTaskCounts() {
  overdueTasks.value = followupSummary.value.reduce((sum, f) => sum + f.overdueFollowups, 0)
  todayTasks.value = followupSummary.value.reduce((sum, f) => sum + f.todayFollowups, 0)
}

/**
 * 重置搜索
 */
function resetSearch() {
  searchForm.keyword = ''
  searchForm.sortBy = 'revenue'
  searchForm.dateRange = [dayjs().startOf('month').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  pagination.page = 1
  fetchData()
}

/**
 * 查看销售员的客户列表
 */
function viewCustomers(row: any) {
-  ElMessage.info(`查看 ${row.name} 的客户列表`)
-  // 这里可以跳转到客户列表页并传递销售员过滤条件
+  router.push({ name: 'CustomerList', query: { salesManager: row.name, title: `${row.name} 的客户` } })
 }

/**
 * 查看销售员的订单详情
 */
function viewOrders(row: any) {
-  ElMessage.info(`查看 ${row.name} 的订单详情`)
-  // 这里可以跳转到订单列表页并传递销售员过滤条件
+  router.push({ name: 'OrderList', query: { title: `${row.name} 的订单` } })
 }

/**
 * 查看销售员数据分析
 */
function viewStats(row: any) {
-  ElMessage.info(`查看 ${row.name} 的数据分析`)
-  // 可以跳转到详细的销售员分析页面
+  router.push({ name: 'AnalyticsCustomer', query: { title: `${row.name} 数据分析` } })
 }

/**
 * 查看跟进详情
 */
function viewFollowupDetails(row: any) {
  ElMessage.info(`查看 ${row.salesman} 的跟进详情`)
}

/**
 * 分配任务
 */
function assignTasks(row: any) {
  ElMessage.info(`为 ${row.salesman} 分配新任务`)
}

/**
 * 导出报表
 */
function exportReport() {
  ElMessage.success('正在生成销售员业绩报表...')
}

/**
 * 初始化业绩图表
 */
function initPerformanceChart() {
  if (!performanceChart.value) return
  
  performanceChartInstance = echarts.init(performanceChart.value)
  
  const option = {
    title: {
      show: false
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月'],
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(万元)',
        position: 'left',
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 0,
        data: [120, 132, 101, 134, 90, 230, 210, 245],
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        data: [45, 52, 38, 48, 35, 78, 72, 85],
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  performanceChartInstance.setOption(option)
}

function onPageChange(p: number) { pagination.page = p }
function onPageSizeChange(s: number) { pagination.pageSize = s; pagination.page = 1 }

onMounted(() => {
  fetchData()
  initPerformanceChart()
})
</script>

<style scoped>
.sales-management { padding: 0; }
.search-card { margin-bottom: 12px; }
.search-bar { display: flex; align-items: center; }

.overview-card {
  margin-bottom: 16px;
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  color: white;
  margin-right: 16px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.card-desc {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 500;
}

.salesman-info {
  display: flex;
  align-items: center;
}

.text-secondary {
  font-size: 12px;
  color: #999;
}

.chart-container {
  height: 300px;
}

.pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>